import Vue from 'vue'
import { ACCESS_TOKEN } from '@/config/storageKey'
import { login, logout, getInfo, getUserMenu } from "@/api/org/user"
import { resetRouter } from '@/router'
/**
 * 用户状态管理
 * light_dust 2020/4/13
 */
const state = {
    token: '',//token
    userId: '',//用户id
    userName: '',//用户名
    avatar: '',//头像
    menus: []//用户菜单
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_USER_ID: (state, userId) => {
        state.userId = userId;
    },
    SET_USER_NAME: (state, userName) => {
        state.userName = userName;
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar;
    },
    SET_MENU: (state, menus) => {
        state.menus = menus;
    }
}

const actions = {
    login({ commit }, userInfo) {
        const { userName, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ userAccount: userName.trim(), userPassword: password }).then(response => {
                const token = response.data.data;
                Vue.ls.set(ACCESS_TOKEN, token, 2 * 60 * 60 * 1000)
                commit('SET_TOKEN', token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // get user info 并设置菜单信息
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(response => {
                const { user, menus } = response.data.data;
                const { userName, userAvatar, userId } = user;
                commit('SET_MENU', menus)
                commit('SET_USER_NAME', userName)
                commit('SET_AVATAR', userAvatar)
                commit('SET_USER_ID', userId)
                resolve(user)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                commit('SET_TOKEN', '')
                commit('SET_USER_NAME', '')
                commit('SET_AVATAR', '')
                commit('SET_USER_ID', '')
                commit('SET_MENU', [])
                Vue.ls.remove(ACCESS_TOKEN)
                resetRouter()
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            Vue.ls.remove(ACCESS_TOKEN)
            resolve()
        })
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}